import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
// 导入窗口自定义移动类
import { AzCustomWindowMove } from './common/azCustomWindowMove'

// 实例化窗口自定义移动类
const customWindowMove = new AzCustomWindowMove()

// let progressInterval
function createWindow(): void {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1088, // 窗口宽度
    height: 616, // 窗口高度
    show: false, // 是否隐藏窗口，默认展示，不展示看不了内容
    autoHideMenuBar: true, // 隐藏菜单栏

    // x: 0, // 窗口左上角x坐标
    // y: 0, // 窗口左上角y坐标
    // maxWidth: 1200, // 最大宽度
    // maxHeight: 800, // 最大高度
    // minWidth: 900, // 最小宽度
    // minHeight: 670, // 最小高度
    resizable: false, // 是否可调整大小
    frame: false, // 是否显示边框(无边框模式只保留主体部分、标题、icon、菜单栏、收起/全屏/关闭选项等全部隐藏)
    // transparent: false, // 是否透明(打开开发者模式时，窗口不透明)
    // title: '项目管理工具', // 窗口标题
    // movable: true, // 是否可移动
    // minimizable: true, // 是否可最小化
    maximizable: false, // 是否可最大化
    // fullscreenable: true, // 是否可全屏
    // closable: true, // 是否可关闭
    
    ...(process.platform === 'linux' ? { icon } : {}), // 设置图标(linux下不设置图标会导致应用图标显示为electron图标)
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
  // 将主窗口传进去
  customWindowMove.init(mainWindow)
}
// 设置标题
function handleSetTitle(event: Electron.IpcMainEvent, title: string): void {
  const webContents = event.sender
  const window = BrowserWindow.fromWebContents(webContents)
  if (window) {
    window.setTitle(title)
  }
}
// 设置进度条
function handleSetProgress(event: Electron.IpcMainEvent, progress: number): void {
  const webContents = event.sender
  const window = BrowserWindow.fromWebContents(webContents)
  if (window) {
    window.setProgressBar(progress)
  }
}
// 窗口移动方法
function handleMove(event: Electron.IpcMainEvent, info: any): void {
  console.log('handleMove', info)
  const operateEvent = info.event || ''
  switch (operateEvent) {
    // 开始移动
    case 'homeDragWindowStart' :{
      /**
       * 如果别的窗口也想复用这个自定义拖拽方法可以这么用
       * const webContents = event.sender
       * const win = BrowserWindow.fromWebContents(webContents)
       * customWindowMove.init(win)
       * customWindowMove.start()
       * break
       */
      customWindowMove.start()
      break
    }
    case 'homeDragWindowEnd' :{
      customWindowMove.end()
      break
    }
    default:
      break
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))
  ipcMain.on('set-title', handleSetTitle) // 设置标题方法暴露给渲染进程
  ipcMain.on('set-progress', handleSetProgress) // 设置进度条方法暴露给渲染进程
  ipcMain.on('Main_Window_Operate', handleMove) // 窗口移动方法暴露给渲染进程

  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('before-quit', () => {
  // clearInterval(progressInterval)
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
